#!/usr/bin/env python
# -*-coding:utf-8 -*-
import pygtk
pygtk.require("2.0")
import gtk
import gobject

import os
import sys
import subprocess
from signal import SIGKILL,SIGTERM
import shlex
import threading
import time

import vlc

import gdata.youtube
import gdata.youtube.service

from playertool import AudioPlayer
from download import Download

class Video:
	"""Types Video"""
	def __init__(self, title='', url='', duration=''):
		self.title = title
		self.url = url
		self.duration = duration

class Audio:
	"""Types Audio"""
	def __init__(self, title='', author='', duration=''):
		self.title = title
		self.author = author
		self.duration = duration

class Stream:
	"""Stream class Search and Play"""
	def __init__(self):
		gobject.threads_init()
		
		#VLC Service
		self.vlcinst = vlc.Instance('--no-video')
		self.player = self.vlcinst.media_player_new()

		#Youtube Service
		yt_service = gdata.youtube.service.YouTubeService()
		yt_service.ssl = True

		#Path information
		self.path = os.path.realpath(sys.argv[0])
		self.path = self.path.replace('youpystream.py','')

		#Gui with glade ;)
		self.interface = gtk.Builder()
		#Import glade file
		try:
			self.interface.add_from_file(self.path+'data/youpystream.glade')
		except:
			print('Can\'t open gui file')
			sys.exit(1)

		self.window1 = self.interface.get_object('window1')
		self.defil_treeview = self.interface.get_object('scrolledwindow1')
		self.entry_search = self.interface.get_object('entry1')
		self.affichage_lecteur = self.interface.get_object('checkmenuitem1')
		self.notebook = self.interface.get_object('notebook1')
		#AudioPlayer
		self.player = AudioPlayer(self.player)
		self.main_box = self.interface.get_object('vbox1')
		#tmp = self.player.get_audioplayer()
		self.main_box.pack_start(self.player,expand=False)
		self.main_box.reorder_child(self.player,1)
		#Treeview search
		self.treestore = gtk.TreeStore(str)
		self.treeview = gtk.TreeView(self.treestore)
		self.treeview.connect('row-activated',self.onSelectMusic)
		self.tvcol = gtk.TreeViewColumn('Résultat')
		self.treeview.append_column(self.tvcol)
		self.cell = gtk.CellRendererText()
		self.tvcol.pack_start(self.cell, True)
		self.tvcol.add_attribute(self.cell, 'text', 0)
		self.defil_treeview.add_with_viewport(self.treeview)
		self.defil_treeview.show_all()

		#NoteBook
		#download_box = Download()
		#self.notebook.append_page(download_box)

		self.interface.connect_signals(self)
		
		#var
		self.list_video = []
		
		#Procces Player
		self.p = None

	def main(self):
		gtk.main()
	
	def onDestroy(self,event):
		if self.p != None:
			print('Kill process : youtube-dl')
			os.kill(self.p.pid,SIGTERM)
		self.player.exit = True
		#delete tempory file
		try:
			os.remove('file')
		except:
			pass

		gtk.main_quit()

	def onActivateSearch(self,event):
		text = self.entry_search.get_text()
		self.searchVideo(text)
	
	def onSelectMusic(self,treeview,itera,chemin):
		if self.player.thread.is_alive():
			self.player.exit = True
			self.player.thread.join()
			self.player.initThread()

		#delete old file
		try:
			os.remove('file')
		except:
			pass

		if self.p != None:
			print('Kill process : youtube-dl')
			os.kill(self.p.pid,SIGTERM)
		print('Selection :')
		print(self.list_video[itera[0]].title)
		url = self.list_video[itera[0]].url
		
		#shell command to start the dl
		try:
			command = self.path+'youtube-dl --no-part -o file '+url
			args = shlex.split(command)
		except:
			print('Download failed')
			sys.exit(1)

		self.p = subprocess.Popen(args)
		continuer = False
		while not continuer:
			for fi in os.listdir('.'):
				if fi == 'file':
					continuer = True
		print('File found')
		while continuer:
			if os.path.getsize('file') > long(500000):
				continuer = False
		print('Ok load file')
		
		self.player.exit = False
		self.player.toolplayer.set_mrl('file')
		self.player.toolplayer.play()
		self.player.thread.start()

	#Affichage Lecteur audio
	def onScreenLecteur(self,event):
		if self.affichage_lecteur.get_active():
			self.player.show()
		else:
			self.player.hide()

	def onFileSearch(self,event):
		self.notebook.set_current_page(0)

	#Youtube API
	def PrintVideoFeed(self,feed):
		for entry in feed.entry:
			PrintEntryDetails(entry)

	def PrintEntryDetails(self,entry):
		print('Video title: %s') % entry.media.title.text

	def makeListVideo(self, feed):
		#del old research
		self.list_video = []
		self.treestore.clear()
		for entry in feed.entry:
			self.list_video.append(Video(entry.media.title.text,
										 entry.GetSwfUrl(),
										 entry.media.duration.seconds))

	def searchVideo(self,search_terms):
		try:
			yt_service = gdata.youtube.service.YouTubeService()
			query = gdata.youtube.service.YouTubeVideoQuery()
			query.vq = search_terms
			#query.orderby = 'viewCount'
			#query.racy = 'include'
			feed = yt_service.YouTubeQuery(query)
			self.makeListVideo(feed)
			#remplissage du treeview en fonction de la recherche
			for elt in self.list_video:
				self.treestore.append(None,[elt.title])
		except:
			print('Research Failed')

if __name__=="__main__":
	app = Stream()
	app.main()

